import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Permission } from '../../entities/permission.entity';

/**
 * 权限服务
 *
 * 职责：
 * 1. 权限的 CRUD 操作
 * 2. 按资源分组查询权限
 * 3. 权限验证
 */
@Injectable()
export class PermissionService {
  constructor(
    @InjectRepository(Permission)
    private readonly permissionRepository: Repository<Permission>,
  ) {}

  /**
   * 创建权限
   *
   * 权限命名规范：资源:操作
   * 例如：product:create, user:delete
   */
  async create(createPermissionDto: {
    name: string;
    displayName: string;
    description?: string;
    resource: string;
    action: string;
  }) {
    // 检查权限是否已存在
    const existing = await this.permissionRepository.findOne({
      where: { name: createPermissionDto.name },
    });

    if (existing) {
      throw new Error('权限已存在');
    }

    const permission = this.permissionRepository.create(createPermissionDto);
    return await this.permissionRepository.save(permission);
  }

  /**
   * 批量创建权限
   * 方便初始化系统权限
   */
  async createBatch(permissions: any[]) {
    const created: Permission[] = [];

    for (const permissionDto of permissions) {
      try {
        const permission = await this.create(permissionDto);
        created.push(permission);
      } catch (error) {
        // 如果已存在，跳过
        console.log(`权限 ${permissionDto.name} 已存在，跳过`);
      }
    }

    return created;
  }

  /**
   * 查找所有权限
   */
  async findAll() {
    return await this.permissionRepository.find({
      order: { resource: 'ASC', action: 'ASC' },
    });
  }

  /**
   * 按资源分组
   *
   * 返回格式：
   * {
   *   product: [
   *     { name: 'product:create', displayName: '创建商品' },
   *     { name: 'product:read', displayName: '查看商品' },
   *   ],
   *   user: [ ... ]
   * }
   */
  async findGroupByResource() {
    const permissions = await this.findAll();

    const grouped = {};
    permissions.forEach((permission) => {
      const resource = permission.resource;
      if (!grouped[resource]) {
        grouped[resource] = [];
      }
      grouped[resource].push(permission);
    });

    return grouped;
  }

  /**
   * 查找单个权限
   */
  async findOne(id: string) {
    const permission = await this.permissionRepository.findOne({
      where: { id },
    });

    if (!permission) {
      throw new NotFoundException('权限不存在');
    }

    return permission;
  }

  /**
   * 根据权限名查找
   */
  async findByName(name: string) {
    return await this.permissionRepository.findOne({
      where: { name },
    });
  }

  /**
   * 根据权限名称数组查找多个权限
   * 用于权限初始化时批量查找
   */
  async findByNames(names: string[]): Promise<Permission[]> {
    if (!names || names.length === 0) {
      return [];
    }

    return await this.permissionRepository
      .createQueryBuilder('permission')
      .where('permission.name IN (:...names)', { names })
      .getMany();
  }

  /**
   * 删除权限
   */
  async remove(id: string) {
    await this.permissionRepository.delete(id);
    return { message: '删除成功' };
  }
}
